/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Game.bc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 *
 * @author Light
 */
@Stateless(mappedName = "GameLogicBean")
    @Interceptors(CallTracer.class)
public class GameLogic implements GameLogicRemote {

    @Resource(name = "jms/sampleQueue")
    private Queue sampleQueue;
    @Resource(name = "jms/sampleQueueFactory")
    private ConnectionFactory sampleQueueFactory;
    @EJB
    private TimerBean timerBean;
    @EJB
    private GameControllerLocal gameController;
    @EJB
    private WordFactoryLocal wordFactory;
    private Player player = null;
    private Game g = null;
    private int timerSeconds = 0;

    public String call(int length) {
        try {
            return wordFactory.getWord(length);
        } catch (Exception ex) {

            Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
            return "Error Aayo";
        }
    }


    public class HelloBean {

        public String sayHello(String message) {
            return "Echo from bean: " + message;
        }
    }

    public BullCow makeGuess(String word, Player player) {

        try {
            sendJMSMessageToSampleQueue("Guess made by player: " + player.getName());
        } catch (JMSException ex) {
            Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
        }

        return g.makeGuess(word, player.getName());
    }

    public String getTheWord() {
        return g.getTheWord();
    }

    public ArrayList<String> getGameList() {
        ArrayList<String> players = new ArrayList<String>();
        HashMap<Player, Game> games = gameController.getGames();
        Iterator iterator = games.keySet().iterator();
        while (iterator.hasNext()) {
            Player key = ((Player) iterator.next());
            Game g = games.get(key);
            String s = key.getName();
            //String s = "Creator :&#9;&#9;" + key.getName() + "| WordLength :&#9;&#9;" + g.getWordLength()+"<br/>";
            players.add(s);
        }
        return players;
    }

    public boolean createGame(int WordLength, Player player) {
        this.player = player;
        timerBean.resetSeconds();
        timerSeconds = timerBean.getSeconds();
        g = gameController.createGame(player, WordLength);
        System.out.println("******** : Game Retrived " + g.getCreator().getName());
        if (g == null) {
            return false;
        } else {
            try {
                g.setTheWord(wordFactory.getWord(WordLength).toLowerCase());
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        }
    }

    public boolean joinGame(String playerName) {
        g = gameController.joinGame(playerName);
        if (g == null) {
            System.out.println("***g = null.***!!!!!!!!!");
            return false;
        } else {
            System.out.println("Joined game with word :" + g.getTheWord());
            return true;
        }
    }

    public String getOutput() {
        return g.getOutput();
    }

    //update and return timer variable
    public int getTimerSeconds() {
        timerSeconds = timerBean.getSeconds();
        return timerSeconds;
    }

    public void resetTimerSeconds() {
        timerBean.resetSeconds();
        timerSeconds = 0;
    }

    private Message createJMSMessageForjmsSampleQueue(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToSampleQueue(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = sampleQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(sampleQueue);
            messageProducer.send(createJMSMessageForjmsSampleQueue(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
